﻿// RSU_Client.cpp: 定义应用程序的入口点。
//

#include <Util/File.h>
#include <bits/types/FILE.h>
#include <csignal>
#include "ChengguRSUClient.h"
#include "ConfigManager.h"
#include "JinyiRSUClient.h"
#include "KafkaClient.h"
#include "SdrRadar.h"
#include "pch.h"

std::string GetCurrentModuleDirectory() {
    char buffer[1024];
    // 根据 OS 调用不同的函数
#ifdef _WIN32
    _getcwd(buffer, sizeof(buffer));
#else
    getcwd(buffer, sizeof(buffer));
#endif
    std::cout << "Current working directory: " << buffer << std::endl;
    return std::string(buffer);
}

int main() {
    auto root = GetCurrentModuleDirectory();
    auto config_file = root + "/config.xml";
    auto log_path = root + "/logs";
    toolkit::File::create_path(log_path, 0777);

    auto console_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
    auto file_path = log_path + "/" + fmt::format("{:%Y%m%d%H%M%S}.log", fmt::localtime(std::time(nullptr)));
    auto file_sink = std::make_shared<spdlog::sinks::rotating_file_sink_mt>(
        file_path, 1024 * 1024 * 50, 12, true);
    auto logger
        = std::make_shared<spdlog::logger>("logger", spdlog::sinks_init_list { console_sink, file_sink });

#if defined(_WIN32) && defined(_MSC_VER)
    auto msvc_sink = std::make_shared<spdlog::sinks::msvc_sink_mt>();
    logger->sinks().push_back(msvc_sink);
#endif

    logger->set_pattern("[%Y-%m-%d %H:%M:%S.%f] [%^%l%$] [%t] [%s:%#] %v");
    spdlog::set_default_logger(logger);
    logger->set_level(spdlog::level::info);

    //加载配置文件
    auto ret = ConfigManager::GetInstance()->LoadConfig(config_file);
    if (!ret)
        return 0;

    auto param = ConfigManager::GetInstance()->GetKafkaParam();
    SPDLOG_INFO("初始化Kafka客户端");
    KafkaClient::GetInstance()->Init(param.URI, param.Topic);
    KafkaClient::GetInstance()->Start();

    SPDLOG_INFO("初始化设备信息");
    auto device_infos = ConfigManager::GetInstance()->GetAllDeviceInfo();
    std::vector<std::shared_ptr<DeviceInterface>> devices;
    for (auto &&info : device_infos) {
        std::shared_ptr<DeviceInterface> device = nullptr;
        if (strcasecmp(info->Manufacturer.c_str(), "Chenggu") == 0) {
            device = std::make_shared<ChengGuRsuClient>();
        } else if (strcasecmp(info->Manufacturer.c_str(), "Jinyi") == 0) {
            device = std::make_shared<JinyiRsuClient>();
        }else if (strcasecmp(info->Manufacturer.c_str(), "sdr") == 0) {
            device = std::make_shared<SdrRadarClient>();
        }

        if (device) {
            device->Init(info);
            device->Start();
            devices.push_back(device);
        }
    }

#ifdef _DEBUG
    getchar();
#else
    static std::promise<void> s_exit;
    signal(SIGINT, [](int signal) {
        SPDLOG_INFO("Catch Signal: {}", signal);
        s_exit.set_value();
    });
    s_exit.get_future().wait();
#endif

    for (auto &&device : devices) {
        device->Stop();
    }

    return 0;
}
